package com.wing.sys.controller;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.wing.cms.domain.Article;
import com.wing.cms.service.ArticleManager;
import com.wing.cms.service.SiteManager;
import com.wing.common.Constants;
import com.wing.common.util.CookieUtils;
import com.wing.common.util.PageBean;
import com.wing.lucene.ArticleIndex;
import com.wing.portal.aggregation.portletinfo.ArticlePortletInfo;
import com.wing.sys.domain.Module;
import com.wing.sys.domain.Operatelog;
import com.wing.sys.domain.User;
import com.wing.sys.service.ModuleManager;
import com.wing.sys.service.OperatelogManager;
import com.wing.sys.service.UserManager;

@Controller
@RequestMapping(value = "/sys")
public class SysController {
	@Autowired
	private UserManager userManager;
	@Autowired
	private SiteManager siteManager;
	@Autowired
	private ModuleManager moduleManager;
	@Autowired
	private OperatelogManager operatelogManager;
	@Autowired
	private ArticleManager articleManager;
	
	@RequestMapping(value = "get/{url}", method = RequestMethod.GET)
	public String get(@PathVariable String url) {
		return url;
	}
	
	@RequestMapping(value = "go/{moduleId}", method = RequestMethod.GET)
	public @ResponseBody String go(@PathVariable String moduleId,HttpServletRequest request) {
		Module m = moduleManager.findById(moduleId);
		if(m==null){
			return "";
		}
		return request.getContextPath()+m.getUrl();
	}

	/**
	 * ajax方式 获取一个组织机构列表 
	 * @return
	 */
	@RequestMapping(value = "getm/{id}", method = RequestMethod.GET)
	public @ResponseBody Module getm(@PathVariable String id) {
		return moduleManager.findById(id);
	}
	
	@RequestMapping(value = "searchdomain", method = RequestMethod.POST)
	public @ResponseBody String searchdomain(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException {
		  InputStream is = null;
	      String s;
	      URLConnection conn = null;
	      try {
	    	 URL u = new URL("http://panda.www.net.cn/cgi-bin/check.cgi?area_domain="+request.getParameter("area_domain"));
	         conn = u.openConnection();
	         conn.setConnectTimeout(3000);
	         is = conn.getInputStream();
	         s = convertStreamToString(is);
	      } catch (MalformedURLException mue) {
	         System.out.println("出错了! 此URL格式不正确.");
	         mue.printStackTrace();
	         return Constants.DEFAULT_AJAX_FAILURE;
	      } catch (IOException ioe) {
	         System.out.println("出错了! 发生IO异常.");
	         ioe.printStackTrace();
	         return Constants.DEFAULT_AJAX_FAILURE;
	      } finally {
	         try {
	        	if(is!=null){
		            is.close();
	        	}
	         } catch (IOException ioe) {
	        	 ioe.printStackTrace();
	         }
	      }
	      return s;
	}
	
	private String convertStreamToString(InputStream is) throws IOException {
         StringBuilder sb = new StringBuilder();
         String line;
         BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
         while ((line = reader.readLine()) != null) {
        	 sb.append(line).append("\n");
         }
         return sb.toString();
	}

	/**
	 * 用户通过登录名跳转到他的网站后台登录页面
	 */
	@RequestMapping(value = "dispatch", method = RequestMethod.POST)
	public @ResponseBody Map dispatch(String login_code,HttpServletRequest request) {
		Map map = new HashMap();
		List users = userManager.findUsersByLoginCode(login_code);
		if(users.size()==0){
			map.put("status",Constants.DEFAULT_AJAX_FAILURE );
			map.put("code","nosite" );
			return map;
		}
		String userId=(String)((Map)users.get(0)).get("id");
		List sites =  siteManager.getSitesBySiteMgrs(userId);
		if(sites.size()==0){
			map.put("status",Constants.DEFAULT_AJAX_FAILURE );
			map.put("code","nosite" );
			return map;
		}
		String url=(String)((Map)sites.get(0)).get("site_url");
		map.put("status",Constants.DEFAULT_AJAX_SUCCESS );
		map.put("url",url );
		map.put("l",(String)((Map)users.get(0)).get("login_code") );
		map.put("p",(String)((Map)users.get(0)).get("password") );
		return map;
	}
	
	/**
	 * 用户验证
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "login", method = RequestMethod.POST)
	public @ResponseBody String login(User user,HttpServletRequest request) {
		String validateC = (String) request.getSession().getAttribute("validateCode");
		String veryCode = request.getParameter("veryCode");
		String a = request.getParameter("a");
		if(!"y".equals(a)){
			if(veryCode==null||"".equals(veryCode)){
				return "codenull";
			}else{
				if(!validateC.equals(veryCode.toUpperCase())){ 
					return "codedif";          
				}              
			}
		}
		Map userMap = userManager.findUser(user.getLogin_code(),user.getPassword());
		if(userMap==null){
			return "failure";
		}

		if(!Constants.SYSTEM_SUPERADMIN_ID.equals((String)userMap.get("id"))){
			//检验用户是否是该域名的管理员
			String url = request.getServerName();
			boolean ismanager=false;
			List sites =  siteManager.getSitesBySiteMgrs((String)userMap.get("id"));
			System.out.println("+++++++"+sites.size()+"+++++"+(String)userMap.get("id")+"+++++++++++++++++++++++++");
			for(int i=0;i<sites.size();i++){
				String siteurl = (String)((Map)sites.get(0)).get("site_url");
				System.out.println("+++++++"+siteurl+"+++++"+url+"+++++++++++++++++++++++++");
				if(url.equals(siteurl)){
					ismanager=true;
				}
			}
			if(!ismanager){
				//检验用户是否是该域名的成员，不是则不让登录
				sites =  siteManager.getSitesBySiteUser((String)userMap.get("id"));
				for(int i=0;i<sites.size();i++){
					String siteurl = (String)((Map)sites.get(0)).get("site_url");
					if(url.equals(siteurl)){
						ismanager=true;
					}
				}
			}
			if(!ismanager){
				return "failure";
			}
		}
		
		User u = userManager.findById((String)userMap.get("id"));
		request.getSession().setAttribute(Constants.SESSION_USER_ID,u.getId());
		request.getSession().setAttribute(Constants.SESSION_USER_NAME,u.getName());
		Operatelog o = new Operatelog();
		o.setDescription(u.getName()+"于"+(new Date())+"登陆");
		o.setLog_time(new Date());
		o.setUser_id(u.getId());
		o.setWork_ip(request.getRemoteAddr());
		o.setSuccess(1);
		operatelogManager.saveOperatelog(o);

		return Constants.DEFAULT_AJAX_SUCCESS;
	}

	
	/**
	 * 退出
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "logout", method = RequestMethod.GET)
	public String logout(HttpServletRequest request) {
		request.getSession().invalidate();
		return "login";
	}
	
	@RequestMapping(value = "getImg", method = RequestMethod.GET)
	public String getImg(HttpServletRequest request,HttpServletResponse response) throws IOException {
		// 验证码图片的宽度。          
		int width = 60;              
		// 验证码图片的高度。         
		int height = 20;               
		// 验证码字符个数          
		int codeCount = 4;               
		         
		// 字体高度 
		int fontHeight = height - 2; 
		int codeY = height - 4;   
		int x1 = width / (codeCount + 1);

		
		char[] codeSequence = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
				'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
				'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
		// 定义图像buffer              
		BufferedImage buffImg = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);
		Graphics2D g = buffImg.createGraphics();                   
		// 创建一个随机数生成器类              
		Random random = new Random();                   
		// 将图像填充为白色              
		g.setColor(Color.WHITE);              
		g.fillRect(0, 0, width, height);                   
		// 创建字体，字体的大小应该根据图片的高度来定。              
		Font font = new Font("Fixedsys", Font.PLAIN, fontHeight);              
		// 设置字体。              
		g.setFont(font);                   
		// 画边框。              
		g.setColor(Color.BLACK);              
		g.drawRect(0, 0, width - 1, height - 1);                   
		// 随机产生160条干扰线，使图象中的认证码不易被其它程序探测到。              
		g.setColor(Color.BLACK);              
		for (int i = 0; i < 0; i++) {                  
			int x = random.nextInt(width);                  
			int y = random.nextInt(height);                  
			int xl = random.nextInt(12);                  
			int yl = random.nextInt(12);                  
			g.drawLine(x, y, x + xl, y + yl);             
		}                   
		// randomCode用于保存随机产生的验证码，以便用户登录后进行验证。              
		StringBuffer randomCode = new StringBuffer();              
		int red = 0, green = 0, blue = 0;                   
		// 随机产生codeCount数字的验证码。              
		for (int i = 0; i < codeCount; i++) {                  
			// 得到随机产生的验证码数字。                  
			String strRand = String.valueOf(codeSequence[random.nextInt(36)]);                 
			// 产生随机的颜色分量来构造颜色值，这样输出的每位数字的颜色值都将不同。                  
			red = random.nextInt(255);                  
			green = random.nextInt(255);                  
			blue = random.nextInt(255);                       
			// 用随机产生的颜色将验证码绘制到图像中。                  
			g.setColor(new Color(red, green, blue));                  
			g.drawString(strRand, (i + 1) * x1, codeY);                       
			// 将产生的四个随机数组合在一起。                  
			randomCode.append(strRand);              
		}              
		// 将四位数字的验证码保存到Session中。              
		HttpSession session = request.getSession();              
		session.setAttribute("validateCode", randomCode.toString());                   
		// 禁止图像缓存。              
		response.setHeader("Pragma", "no-cache");              
		response.setHeader("Cache-Control", "no-cache");              
		response.setDateHeader("Expires", 0);                   
		response.setContentType("image/jpeg");                  
		// 将图像输出到Servlet输出流中。              
		ServletOutputStream sos = response.getOutputStream();              
		ImageIO.write(buffImg, "jpeg", sos);              
		sos.close();
		
		return null;
	}

	@SuppressWarnings("unchecked")
	@RequestMapping(value = "fullTextSearch", method = RequestMethod.POST)
	public @ResponseBody PageBean fullTextSearch(String grpid,String s,int currentPage, String pageSize,HttpServletRequest request) {
		String siteId = (String)request.getSession().getAttribute(Constants.SESSION_SITE_ID);
		int _iPageSize = 0;
		if (pageSize == null) {
			_iPageSize = PageBean.DEFAULT_PAGESIZE;
		} else {
			_iPageSize= Integer.parseInt(pageSize);
		}
		ArticleIndex index = new ArticleIndex();
		PageBean pageBeanSearchImpl = new PageBean();
		try {
			Map search = index.searchArticle(s, currentPage, _iPageSize, siteId);
			int allRow = (Integer)search.get("count"); // 总记录数
			List<String> artids = (List<String>)search.get("artids");
			List<Map<String, Object>>  datalist = new ArrayList<Map<String, Object>>();
			for(int i = 0; i < artids.size(); i ++){
				Article artObject = articleManager.findById((String)artids.get(i));
				Map<String, Object> artMap = new HashMap<String, Object>();
				artMap.put("id", artObject.getId());
				artMap.put("art_name", artObject.getArt_name());
				artMap.put("summary", artObject.getSummary());
				artMap.put("create_user", artObject.getCreate_time());
				artMap.put("showTitle", artObject.getShowTitle());
				
				String imgSrc = ArticlePortletInfo.parsingImgUrl(artObject.getContent());
				artMap.put("firtImgrSrc", imgSrc);
				datalist.add(artMap);
			}			
			int totalPage = PageBean.countTotalPage(_iPageSize, allRow); // 总页数
			
			pageBeanSearchImpl.setPageSize(_iPageSize);
			pageBeanSearchImpl.setCurrentPage(currentPage);
			pageBeanSearchImpl.setAllRow(allRow);
			pageBeanSearchImpl.setTotalPage(totalPage);
			pageBeanSearchImpl.setRecordList(datalist);
			pageBeanSearchImpl.init();
		} catch (IOException e1) {
			e1.printStackTrace();
		} catch (Exception e1){
			e1.printStackTrace();
		}
		return pageBeanSearchImpl;
	}
	
	
	@RequestMapping(value = "getcoo", method = RequestMethod.POST)
	public @ResponseBody String getCookie(HttpServletRequest request,HttpServletResponse response,String k) {
		String v = CookieUtils.getCookie( request, k);
		if(v==null){
			return Constants.DEFAULT_AJAX_FAILURE;
		}
		return v;
	}
	@RequestMapping(value = "setcoo", method = RequestMethod.POST)
	public @ResponseBody String setCookie(HttpServletRequest request,HttpServletResponse response,String k,String v) throws IOException {
		CookieUtils.setCookie( response, k, v,60*60);
		return Constants.DEFAULT_AJAX_SUCCESS;
	}
}
